package com.example.wengwyue.patientapplication.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.wengwyue.patientapplication.R;
import com.example.wengwyue.patientapplication.Session.Session;
import com.example.wengwyue.patientapplication.controller.ActivityController;
import com.example.wengwyue.patientapplication.model.LoginInfo;
import com.example.wengwyue.patientapplication.network.ApiManager;
import com.example.wengwyue.patientapplication.utils.Md5Util;
import com.google.gson.Gson;
import com.hospital.common.api.DataCallback;
import com.hospital.common.api.PublicKeyManager;
import com.hospital.common.api.SimpleCallback;
import com.hospital.common.api.UserEntityKeeper;
import com.hospital.common.api.model.Error;
import com.hospital.common.api.model.UserKeeper;
import com.hospital.common.api.secure.AESKey;
import com.hospital.common.api.secure.SoftDog;

import butterknife.ButterKnife;

/**
 * 作者： wengwyue   时间： 16/7/30.
 * 功能：
 * 修改：
 */
public class LoginActivity extends BaseVaryViewActivity implements View.OnClickListener {
    TextView mRegisterTextView;
    TextView mForgetPswTextView;
    private View mContentView;
    private EditText inputName;
    private EditText inputPasswd;
    private Button loginButton;
    private String name;
    private String passwd;
    private LoginInfo info;

    @Override
    public View provideDataView() {
        return mContentView;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        mContentView = findViewById(R.id.rootView);
        inputName = (EditText) findViewById(R.id.user_name_edit);
        inputPasswd = (EditText) findViewById(R.id.user_password_edit);
        loginButton = (Button) findViewById(R.id.login_button);
        mRegisterTextView = ButterKnife.findById(this, R.id.register_textView);
        mForgetPswTextView = ButterKnife.findById(this, R.id.forget_psw_textView);

        super.initView(savedInstanceState);
    }

    @Override
    protected int provideLayoutResId() {
        return R.layout.activity_login;
    }

    @Override
    protected void initListener() {
        loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 请求登录信息
                name = inputName.getText().toString();
                passwd = inputPasswd.getText().toString();
                checkInputDataIsOk();

            }
        });

        mRegisterTextView.setOnClickListener(this);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        if (Session.instance().isLogin()) {
            ActivityController.goToMain(this);
            finish();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.register_textView:
                startActivity(new Intent(this, RegisterActivity.class));
                break;
        }
    }

    private void checkInputDataIsOk() {

        if (TextUtils.isEmpty(name)) {
            Toast.makeText(this, "用户名不能为空！", Toast.LENGTH_LONG).show();
            return;
        }
        if (TextUtils.isEmpty(passwd)) {
            Toast.makeText(this, "密码不能为空！", Toast.LENGTH_LONG).show();
            return;
        }
        getPublicKey();
    }

    private void getPublicKey() {
        PublicKeyManager.getRSAPubKey(new SimpleCallback<String>() {
            @Override
            public void success(String data) {
                try {
                    info = new LoginInfo(name, Md5Util.makeMd5Sum(new String(passwd).getBytes()));
                    String mSalt = SoftDog.encodeRSA(new Gson().toJson(info), data);
                    login(mSalt);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void failure(String error) {
                Toast.makeText(LoginActivity.this, "网络失败！", Toast.LENGTH_LONG).show();
            }
        });
    }

    private void login(String data) {
        ApiManager.login(data, new DataCallback() {
            @Override
            public void onSuccess(Object data) {
                Error error = (Error) data;
                if (error != null) {
                    if (!error.hasError) {
                        Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_LONG).show();
                        if (info != null) {
                            AESKey aeskey = SoftDog.getAESKey(info.salt.toString());
//                        Log.d("key", "login:key.key" + aeskey.key);
//                        Log.d("key", "login:key.vi" + aeskey.vi);
                            UserKeeper keeper = new UserKeeper();
                            keeper.key = aeskey;
                            keeper.name = info.name;
                            UserEntityKeeper.writeAccessToken(keeper);
                            ActivityController.goToMain(LoginActivity.this);
                        }
                    }
                }
                finish();
            }

            @Override
            public void onFailed(Error error) {
                Toast.makeText(LoginActivity.this, error.des, Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
    }
}
